
import store from './store'
import router from './router'
const loginPath = '/login-page'
const whiteList = ['/partylogincb']
const whiteList2 = [ '/third-login', '/over-device', '/introduct', '/introduct-before-tip-login', '/introduct-after-tip-login', '/introduct-tip-buy', '/account-abnormal', '/right-open' ]
function toNextZh (to, next) {
  if (!store.getters.hasLogin && /^\/login/.test(to.redirectedFrom)) {
    const loginType = to.query.type || 'wxLogin'
    store.dispatch('user/login', { type: loginType })
  }
  next()
}
function toNextFn (to, next) {
  if (!store.getters.hasLogin && to.path !== loginPath) {
    next({
      path: loginPath,
      query: {
        type: 'emailLogin'
      },
      replace: true
    })
  } else if (store.getters.hasLogin && to.path === loginPath) {
    next({
      path: '/usercenter',
      replace: true
    })
  } else {
    next()
  }
}
function toNext (to, next) {
  if (process.env.VUE_APP_NAME === 'i18n') {
    toNextFn(to, next)
  } else {
    toNextZh(to, next)
  }
}
router.beforeEach(async (to, from, next) => {
  if (whiteList.includes(to.path)) {
    return next()
  }
  if (!store.getters.appInfo.uuid) {
    await store.dispatch('system/initDeviceInfo').catch(() => {})
  }
  if (whiteList2.includes(to.path)) {
    return next()
  }
  if (!store.getters.token) {
    await store.dispatch('user/getToken').catch(() => {})
  }
  if (store.getters.token && !store.getters.hasLogin) {
    await store.dispatch('user/checkStatus', true).catch(() => {})
  }
  toNext(to, next)
})
